package com.fengyi.library.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 图书API控制器
 * 提供REST API供OpenFeign调用
 */
@RestController
@RequestMapping("/api/books")
public class BookApiController {

    @Value("${server.port}")
    private String serverPort;

    // 模拟图书数据库
    private static final Map<Long, Map<String, Object>> BOOK_DATABASE = new HashMap<>();

    // 静态初始化模拟数据
    static {
        for (long i = 1; i <= 10; i++) {
            Map<String, Object> book = new HashMap<>();
            book.put("id", i);
            book.put("title", "图书" + i);
            book.put("author", "作者" + i);
            book.put("description", "这是第" + i + "本图书的详细描述，包含了图书的内容简介。");
            book.put("isbn", "978-7-" + (10000 + i));
            book.put("publishDate", new Date().toString());
            book.put("price", 30 + i * 5);
            book.put("availableQuantity", 10);
            BOOK_DATABASE.put(i, book);
        }
    }

    /**
     * 获取所有图书
     * @return 图书列表
     */
    @GetMapping
    public List<Map<String, Object>> getAllBooks() {
        List<Map<String, Object>> books = new ArrayList<>(BOOK_DATABASE.values());
        // 添加服务实例信息
        books.forEach(book -> book.put("servicePort", serverPort));
        return books;
    }

    /**
     * 根据ID获取图书
     * @param id 图书ID
     * @return 图书信息
     */
    @GetMapping("/{id}")
    public Map<String, Object> getBookById(@PathVariable Long id) {
        Map<String, Object> book = BOOK_DATABASE.get(id);
        if (book != null) {
            // 创建副本，避免修改原始数据
            book = new HashMap<>(book);
            book.put("servicePort", serverPort);
            return book;
        } else {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "图书不存在");
            error.put("id", id);
            error.put("servicePort", serverPort);
            return error;
        }
    }

    /**
     * 根据标题搜索图书
     * @param title 图书标题
     * @return 图书列表
     */
    @GetMapping("/search")
    public List<Map<String, Object>> searchBooksByTitle(@RequestParam String title) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Map<String, Object> book : BOOK_DATABASE.values()) {
            String bookTitle = (String) book.get("title");
            if (bookTitle != null && bookTitle.contains(title)) {
                // 创建副本，避免修改原始数据
                Map<String, Object> bookCopy = new HashMap<>(book);
                bookCopy.put("servicePort", serverPort);
                result.add(bookCopy);
            }
        }
        
        return result;
    }

    /**
     * 添加图书
     * @param bookInfo 图书信息
     * @return 添加结果
     */
    @PostMapping
    public Map<String, Object> addBook(@RequestBody Map<String, Object> bookInfo) {
        // 生成新的图书ID
        long newId = BOOK_DATABASE.size() + 1;
        while (BOOK_DATABASE.containsKey(newId)) {
            newId++;
        }
        
        // 设置图书ID
        bookInfo.put("id", newId);
        
        // 保存图书
        BOOK_DATABASE.put(newId, bookInfo);
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "图书添加成功");
        result.put("id", newId);
        result.put("servicePort", serverPort);
        return result;
    }

    /**
     * 更新图书
     * @param id 图书ID
     * @param bookInfo 图书信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateBook(@PathVariable Long id, @RequestBody Map<String, Object> bookInfo) {
        Map<String, Object> result = new HashMap<>();
        
        if (BOOK_DATABASE.containsKey(id)) {
            // 更新图书信息
            bookInfo.put("id", id);  // 确保ID不变
            BOOK_DATABASE.put(id, bookInfo);
            
            result.put("success", true);
            result.put("message", "图书更新成功");
        } else {
            result.put("success", false);
            result.put("message", "图书不存在，无法更新");
        }
        
        result.put("id", id);
        result.put("servicePort", serverPort);
        return result;
    }

    /**
     * 删除图书
     * @param id 图书ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteBook(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        if (BOOK_DATABASE.containsKey(id)) {
            // 删除图书
            BOOK_DATABASE.remove(id);
            
            result.put("success", true);
            result.put("message", "图书删除成功");
        } else {
            result.put("success", false);
            result.put("message", "图书不存在，无法删除");
        }
        
        result.put("id", id);
        result.put("servicePort", serverPort);
        return result;
    }
} 